package down.xiaoheihe.work.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import down.xiaoheihe.work.Entity.TProduct;
import down.xiaoheihe.work.Entity.Timages;
import down.xiaoheihe.work.Response.ESproduct;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ElasticUtils {
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    public void 创建索引(TProduct product, List<Timages> images) throws IOException {
        ESproduct eSproduct = new ESproduct(product, images);
        //1、构建请求
        IndexRequest request = new IndexRequest("products_index");
        //2、设置规则  PUT /user_index/user/_doc/1
        //设置id
        request.id(String.valueOf(product.getId()));
        //设置超时时间
        request.timeout(TimeValue.timeValueSeconds(1));
        //3、将数据放入到请求中,以JSON的格式存放
        String json = JSONObject.toJSONString(eSproduct);
        request.source(json, XContentType.JSON);
        //4、客户端发送请求,获取响应结果
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        //5、打印
        System.out.println("创建成功：" + response.toString());
    }

    /**
     * 从ES数据库中按照指定的字符串搜索商品
     *
     * @param value 搜索内容
     */
    public List<Object> find(String value) throws IOException {
        //1、构建搜索请求
        SearchRequest request = new SearchRequest("products_index");
        //2、设置搜索条件，使用该构建器进行查询
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //3、构建精确匹配查询条件
        //4、构建模糊匹配查询条件
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(value, "product.description", "product.title");
        sourceBuilder.query(multiMatchQueryBuilder);
        //5、设置超时
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //6、将搜索条件放入搜索请求中
        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        return getResult1(response);
    }
    /**
     * 从ES数据库里搜索所有商品
     */
    public List<Object> findAll() throws IOException {
        SearchRequest request = new SearchRequest("products_index");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //3、构建精确匹配查询条件
        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        sourceBuilder.query(matchAllQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        return getResult1(response);
    }
    private List<Object> getResult1(SearchResponse response) {
        List<Object> result = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            Map map = (Map) sourceAsMap.get("product");
            Integer status = (Integer) map.get("status");
            if (status == 1) {
                result.add(hit.getSourceAsMap());
            }
        }
        return result;
    }
    private List<Object> getResult(SearchResponse response) {
        List<Object> result = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            result.add(hit.getSourceAsMap());
        }
        return result;
    }
    /**
     * 更新ES数据库里的商品文档
     * @param product 要更新的商品数据，只更新不为null的字段,要求必须有id
     */
    public void updateProducts(TProduct product) throws IOException {
        String id = String.valueOf(product.getId());
        ESproduct esproduct = new ESproduct(product);
        String json = JSON.toJSONString(esproduct);
        UpdateRequest updateRequest =
                new UpdateRequest("products_index", id)
                        .doc(json, XContentType.JSON);
        client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println("更新成功："+json);
    }
    public void 更新指定文档(TProduct tProduct,List<Timages> timages) throws IOException {
        ESproduct esproduct = new ESproduct(tProduct,timages);
        String json = JSON.toJSONString(esproduct);
        String id = String.valueOf(tProduct.getId());
        UpdateRequest updateRequest =
                new UpdateRequest("products_index", id)
                        .doc(json, XContentType.JSON);
        client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println("更新成功："+json);
    }




}